<template>
    <div>
        <el-button @click="$router.push({name: 'kaodian_edit'})" type="primary">新增考点</el-button>
        <br><br>

        <el-table
          :data="list"
          border
          row-key="id"
          :tree-props="{
            children: 'child',
            hasChildren: 'hasChildren'
          }"
        >
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="下属数量" prop="sub_amount"></el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-link @click="add(scope.row.id, scope.row.point_rule)">新增</el-link>
              -
              <el-link @click="$router.push({name: 'kaodian_edit', query:{id: scope.row.id}})">编辑</el-link>
              -
              <el-link>删除</el-link>
            </template>
          </el-table-column>
        </el-table>
    </div>
</template>
<script>
import axios from 'axios'
export default {
  name: '',
  data() {
    return {
      list: []
    }
  },
  created() {
    axios.get('/exam/point').then(res => {
      if (res) {
        this.list = res.data
      }
    })
  },
  mounted() {
  },
  methods: {
    add(id, pointRule) {
      // 先找出父分类名称
      const parentName = this.getParentName(pointRule)

      // 跳转
      this.$router.push({
        name: 'kaodian_edit',
        query: {
          parent_id: id,
          parentName
        }
      })
    },
    // 根据 point_rule 字段查找父分类名称
    getParentName(pointRule) {
      // 把  '/71/72/75'  转成  [71,72,75]  数组
      const arr = pointRule.substr(1).split('/')
      // 所有的数据的数组
      let data = this.list
      let dataA // 找出来的数据
      let val // 每次从数组中取出的值
      // 当数组中还有元素时就一直循环
      while (arr.length > 0) {
        // 从数组中取出第1个元素并从数组中删除
        val = arr.shift()
        // 到数据中根据这个ID找出这条记录
        dataA = data.find(v => v.id == val)
        // 让 data 等于这条记录的 child
        data = dataA.child
      }
      // 把找到的结果返回
      return dataA.name
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>
</style>
